package com.yaozheng.vocationaltraining.fragment;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.yaozheng.vocationaltraining.R;
import com.yaozheng.vocationaltraining.activity.HomeActivity;
import com.yaozheng.vocationaltraining.adapter.PaperCatalogAdapter;
import com.yaozheng.vocationaltraining.iview.IItemView;
import com.yaozheng.vocationaltraining.iview.ILoadMoreView;
import com.yaozheng.vocationaltraining.iview.ITokenBaseView;
import com.yaozheng.vocationaltraining.manage.ListViewLoadMoreManage;
import com.yaozheng.vocationaltraining.service.PaperCatalogService;
import com.yaozheng.vocationaltraining.service.impl.PaperCatalogServiceImpl;
import com.yaozheng.vocationaltraining.utils.Constants;
import com.yaozheng.vocationaltraining.utils.ErrorUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;

@EFragment(R.layout.fragment_paper_catalog)
public class PaperCatalogFragment extends BaseFragment implements
        ITokenBaseView, SwipeRefreshLayout.OnRefreshListener, ILoadMoreView,
        IItemView {
    @ViewById
    ListView listView;

    @ViewById
    TextView headTitleText;
    String examType;
    /**
     * 试卷服务
     */
    @Bean(PaperCatalogServiceImpl.class)
    PaperCatalogService paperCatalogService;
    /**
     * 下拉刷新
     */
    @ViewById
    SwipeRefreshLayout swipeRefreshLayout;
    /**
     * 设备器
     */
    PaperCatalogAdapter paperCatalogAdapter;

    ListViewLoadMoreManage listViewLoadMoreManage;

    int lastId;

    public HomeActivity getHomeActivity() {
        return (HomeActivity) getActivity();
    }

    @AfterViews
    public void initView() {
        headTitleText.setText("考试");
        // listView.setAdapter(new PaperCatalogAdapter(
        // (BaseActivity) getActivity()));

        examType = getBaseActivity().getIntentString("examType");
        paperCatalogService.init(this);
//        swipeRefreshLayout.postDelayed(new Runnable() {
//
//            @Override
//            public void run() {
//                swipeRefreshLayout.setRefreshing(true);
//                onRefresh();
//
//            }
//        }, 500);
        onRefresh();
        swipeRefreshLayout.setOnRefreshListener(this);
        listViewLoadMoreManage = new ListViewLoadMoreManage(this,
                getBaseActivity(), listView);
    }

    /**
     * 加载数据
     */
    public void loadData() {
        if ("1".equals(examType)) {
            // 每日一测
            paperCatalogService.quizzesList(lastId);
        } else {
            // 预习/随堂检测
            paperCatalogService.examList(lastId);
        }
    }

    @UiThread
    @Override
    public void responseSuccess(JSONObject jsonObject) {
        cancelLoadDataProgressDialog();
        JSONArray papersList = TypeUtils.getJsonArray(jsonObject,// "data",
                "papers");

        if (papersList != null) {
            if (paperCatalogAdapter == null) {
                paperCatalogAdapter = new PaperCatalogAdapter(
                        getBaseActivity(), papersList, this);
                listView.setAdapter(paperCatalogAdapter);

            } else {
                if (lastId == 0) {
                    paperCatalogAdapter.getDataList().clear();
                }
                paperCatalogAdapter.getDataList().addAll(papersList);
                paperCatalogAdapter.notifyDataSetChanged();
            }
        }
    }

    @UiThread
    @Override
    public void responseError(String error) {
        cancelLoadDataProgressDialog();
        alertMessage(error);
    }

    @Override
    public void cancelLoadDataProgressDialog() {
        swipeRefreshLayout.setRefreshing(false);
        listViewLoadMoreManage.loadMoreComplete();
    }

    @Override
    public void onRefresh() {
        lastId = 0;
        loadData();
    }

    @Override
    public boolean isResponseResult() {
        return isAdded();
    }

    @Override
    public void loadMoreData() {
        if (paperCatalogAdapter != null) {
            int lastId = paperCatalogAdapter.getLastId();
            if (lastId > 0) {
                this.lastId = lastId;
                loadData();
            }
        }
    }

    @Override
    public void itemClick(int position) {
        if (paperCatalogAdapter != null) {
            JSONObject itemData = TypeUtils.getJsonObject(
                    paperCatalogAdapter.getDataList(), position);
            Intent intent =
                    getBaseActivity().getIntent();
            //new Intent();
            intent.setClassName(getContext(),
                    Constants.ONLINE_EXAM_ACTIVITY_CLASS_NAME);
            intent.putExtra("examType", examType);
            intent.putExtra("paperId", TypeUtils.getJsonInteger(itemData, "id"));
            intent.putExtra("startTime",
                    TypeUtils.getJsonString(itemData, "startTime"));
            //  "2016-06-02 00:12:44 BX7随堂检测".substring(20)
            String subject = TypeUtils.getJsonString(itemData, "subject");
            String examTitle;
            try {
                examTitle = subject.substring(20);
            } catch (Exception ex) {
                ErrorUtils.outErrorLog(ex);
                examTitle = subject;
            }
            intent.putExtra("examTitle", examTitle);
//            startActivityForResult(intent, Constants.ONLINE_EXAM_RESULT_CODE);
            getHomeActivity().openOnlineExamFragment();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.ONLINE_EXAM_RESULT_CODE
                && resultCode == Constants.ONLINE_EXAM_CARRY_OUT_AN_ASSIGNMENT_REQUEST_CODE) {
            swipeRefreshLayout.setRefreshing(true);
            onRefresh();
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onDestroyView() {
        paperCatalogAdapter = null;
        super.onDestroyView();
    }

}
